package com.scholarship.system.controller;

import com.scholarship.system.common.dto.Result;
import com.scholarship.system.service.RankingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 排名控制器
 */
@RestController
@RequestMapping("/ranking")
public class RankingController {

    private static final Logger logger = LoggerFactory.getLogger(RankingController.class);

    @Autowired
    private RankingService rankingService;

    /**
     * 生成学生排名
     *
     * @param year     年份
     * @param semester 学期
     * @return 结果
     */
    @PostMapping("/generate")
    public Result<Void> generateRanking(@RequestParam(required = false) Integer year,
            @RequestParam(required = false) String semester) {
        return rankingService.generateRanking(year, semester);
    }

    /**
     * 获取学生排名列表
     *
     * @param college  学院
     * @param major    专业
     * @param grade    年级
     * @param keyword  关键字
     * @param year     年份
     * @param semester 学期
     * @return 排名列表
     */
    @GetMapping("/list")
    public Result<List<Map<String, Object>>> getRankingList(@RequestParam(required = false) String college,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) String semester) {
        return rankingService.getRankingList(college, major, grade, keyword, year, semester);
    }

    /**
     * 导出排名为Excel
     *
     * @param college  学院
     * @param major    专业
     * @param grade    年级
     * @param keyword  关键字
     * @param year     年份
     * @param semester 学期
     * @param token    认证令牌（可选）
     * @param response HTTP响应
     * @return 结果
     */
    @GetMapping("/export")
    public void exportRankingToExcel(@RequestParam(required = false) String college,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) String semester,
            @RequestParam(required = false) String token,
            HttpServletResponse response) {
        try {
            logger.info("接收到导出排名请求: college={}, major={}, grade={}, keyword={}, year={}, semester={}",
                    college, major, grade, keyword, year, semester);

            // 设置CORS头，允许来自任何源的请求
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

            // 在单独的线程中处理导出，避免阻塞主线程
            rankingService.exportRankingToExcel(college, major, grade, keyword, year, semester, response);

            logger.info("导出排名请求已提交处理");
        } catch (Exception e) {
            logger.error("导出排名控制器异常", e);
            try {
                if (!response.isCommitted()) {
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.getWriter().write("{\"code\":500,\"msg\":\"导出排名失败: " + e.getMessage() + "\"}");
                    response.getWriter().flush();
                }
            } catch (IOException ex) {
                logger.error("写入错误响应异常", ex);
            }
        }
    }

    /**
     * 获取学院列表
     *
     * @return 学院列表
     */
    @GetMapping("/colleges")
    public Result<List<String>> getCollegeList() {
        return rankingService.getCollegeList();
    }

    /**
     * 根据学院获取专业列表
     *
     * @param college 学院
     * @return 专业列表
     */
    @GetMapping("/majors")
    public Result<List<String>> getMajorListByCollege(@RequestParam String college) {
        return rankingService.getMajorListByCollege(college);
    }

    /**
     * 根据专业获取年级列表
     *
     * @param major 专业
     * @return 年级列表
     */
    @GetMapping("/grades")
    public Result<List<String>> getGradeListByMajor(@RequestParam String major) {
        return rankingService.getGradeListByMajor(major);
    }
}